var $,
    layer,
    form,
    upload,
    table;

layui.use(['jquery', 'layer', 'table', 'form', 'upload'], function () {
    $ = layui.jquery,
        layer = layui.layer,
        form = layui.form,
        upload = layui.upload,
        table = layui.table;

    //是否启用
    form.on('switch(online)', function (data) {
        var name = data.value;
        var id = name.substring(0, name.indexOf('-'));
        name = name.substring(name.indexOf('-') + 1, name.lastIndexOf('-'));
        if (data.elem.checked) {
            layer.open({
                type: 0,
                content: '您确定要上架' + name + '吗？',
                area: ['300px', '190px'],
                btn: ['确定', '取消'],
                yes: function (index, layero) {
                    layer.msg('上架成功', {icon: 6});
                    updateOnline(id, 2)
                },
                btn2: function (index, layero) {
                    layer.msg('上架取消', {icon: 5});
                    $('input[value=' + data.value + ']').siblings('.layui-unselect').removeClass('layui-form-onswitch');
                    data.elem.checked = false;
                }
            });
        } else {
            layer.open({
                type: 0,
                content: '您确定要下架' + name + '吗？',
                area: ['300px', '190px'],
                btn: ['确定', '取消'],
                yes: function (index, layero) {
                    layer.msg('下架成功', {icon: 5});
                    updateOnline(id, 3)
                },
                btn2: function (index, layero) {
                    layer.msg('下架取消', {icon: 6});
                    $('input[value=' + data.value + ']').siblings('.layui-unselect').addClass('layui-form-onswitch');
                    data.elem.checked = true;
                }
            });
        }
    });

    function updateOnline(id, online){
        var user =JSON.parse(localStorage.getItem('user'));
        $.ajax({
            url: '/UserCoupon/updateUserCoupon',
            type: 'post',
            dataType: 'json',
            data: {
                'couponId': id,
                'online': online,
                'updateId': user.userId,
            },
            success: function (item) {
               if (item.data){
                    getUseCouponData();
               };
            }
        });
    };
});


//查询用户信息
getUseCouponData();
function getUseCouponData(couponName, grant, online, startDate, endDate){
    $.ajax({
        url: '/UserCoupon/getAllTable',
        type: 'post',
        dataType: 'json',
        data: {
            'couponName': couponName,
            'grant': grant,
            'online': online,
            'startDate': startDate,
            'endDate': endDate
        },
        success: function (item) {
            getUserCouponTable(item.data);
        }
    });
};

//展示用户表
function getUserCouponTable(data) {
    table.render({
        elem: '#demo',
        data: data,
        toolbar: true,
        page:{//自定义分页
            layout:['count','prev','page','next','limit','skip','refresh'],
            limits:[3,6,9],//分页选项
            first:"首页",
            last:"尾页",
        },
        cols: [[
            {type: 'checkbox'},
            {field:'couponName',title:'优惠券名称', align:'center'},
            {field:'startDate',title:'开始时间',align:'center'},
            {field:'endDate',title:'结束时间',align:'center'},
            {field:'online',title:'上架/下架',align:'center', templet: function (data) {
                    if (data.online == 2){
                        return '<input type="checkbox" name="switch" value="'+data.couponId+'-'+data.couponName+'" lay-filter="online" lay-text="上架 | 下架" lay-skin="switch" checked>'
                    } else{
                        return '<input type="checkbox" name="switch" value="'+data.couponId+'-'+data.couponName+'" lay-filter="online" lay-text="上架 | 下架" lay-skin="switch">'
                    }
                }},
            {field:'grant',title:'发放方式',align:'center'},
            {field:'issueQuantity',title:'发行数',align:'center'},
            {field:'',title:'剩余数',align:'center', templet: function (data) {
                return data.issueQuantity - data.used;
                }},
            {title:'操作',align:'center', templet:function(data){
                    return "<a href='JavaScript:getUseCouponr(\"" + data.couponId +  "\");' class='operation'>查看</a>" + '&nbsp;&nbsp;'
                        +"<a class='operation' href='javascript:deleteUserCoupon(\"" + data.couponId + "\");'>删除</a>";
                }},
        ]]
    });
};

//搜索
function search () {
    var data = form.val('searchForm');
    if (data.deptName != null && data.deptName != ''){
        $.ajax({
            url: '/Dept/getNameById',
            type: 'post',
            data: {'deptName': data.deptName},
            dataType: 'json',
            async: false,
            success: function (item) {
                data.deptName = item.data;
            }
        })
    }
    getUseCouponData(data.couponName, data.grant, data.online)
};



//高级检索
function accurate(){
    layer.open({
        type:2,
        title: '高级检索',
        content:"/coupon/couponList-precisesearch.html",
        area:['490px','500px'],
    })
};

//查看用户
function getUseCouponr(id) {
    layer.open({
        type: 2,
        offset: 'auto',
        resize: false,
        maxmin: true,
        title: '优惠券详情',
        area: ['800px', '540px'],
        content: '/coupon/layer/layer-couponList-selectUserCoupon.html?tx=' + encodeURI(id),
    });
};

//删除
function deleteUserCoupon(id) {
    layer.open({
        type:1,
        content:"<div style='font-size: 20px ; color: red; margin:30px  ;'>是否删除此商品?</div>",
        area:['300px','200px'],
        btn:["确定","取消"],
        yes: function (index,layero) {
            $.ajax({
                url: '/UserCoupon/deleteUserCoupon',
                type: 'post',
                dataType: 'json',
                data: {
                    'couponId': id
                },
                success: function (item) {
                    if (item.data){
                        layer.msg('删除成功');
                        getUseCouponData();
                    } else{
                        layer.msg('删除失败');
                    }
                }
            });
        },
        btn2: function (index,layero) {
            layer.close(index);
        }
    });

};

//添加用户
function addCoupon() {
    location.href='addCopuon.html';
}


//刷新
function refresh () {
    location.reload();
};
function backOff() {
    var arr = localStorage.getItem("numArr");
    var numArr = arr.split(",");
    numArr.pop();
    window.parent.layui.element.tabChange('tab',numArr[numArr.length - 1]);
    localStorage.setItem("numArr",numArr);
};